//
//  HWGiftBagCenterController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/9/22.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
class HWGiftBagCenterController: HWBaseViewController {
    var searchBgView:UIView!
    var searchLogo:UIImageView!
    var searchField:UITextField!
    var collectionView:UICollectionView!
    let collectionProtocol = HWGiftBagCenterProtocol()
    let httpManager = HWGiftBagCenterHttpManager()
    var keyword = ""
    var modelArr:[HWGiftBagCenterModel] = []
    let alert = HWGiftBagCenterDetailAlert()
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        loadData()
        
        addRefresh()
        
        addAction()
        
    }
}

extension HWGiftBagCenterController {
    private func initUI() -> Void {
        
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        
        navigationView.titleLabel.text = "礼包中心"
        navigationView.backButton.setImage(UIImage(named: "navBackButton"), for: .normal)
        
        view.backgroundColor = .colorWithHexString(hexString: "#F7F7F7")
        
        searchBgView = UIView()
        searchBgView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        searchBgView.layer.cornerRadius = 17*widthScale
        searchBgView.layer.masksToBounds = true
        view.addSubview(searchBgView)
        
        searchLogo = UIImageView()
        searchLogo.image = UIImage(named: "giftBagSearchLogo")
        searchBgView.addSubview(searchLogo)
        
        searchField = UITextField()
        searchField.placeholder = "搜索感兴趣的游戏"
        searchField.delegate = self
        searchField.returnKeyType = .search
        searchField.font = .systemFont(ofSize: 13*widthScale)
        searchField.textColor = .colorWithHexString(hexString: "#333333")
        searchField.addTarget(self, action: #selector(searchTextFieldChange(_:)), for: .editingChanged)
        searchBgView.addSubview(searchField)
        
        let flowL = UICollectionViewFlowLayout.init()
        flowL.minimumLineSpacing = 0
        flowL.minimumInteritemSpacing = 0
        flowL.scrollDirection = .vertical
        collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowL)
        collectionView.delegate = collectionProtocol
        collectionView.dataSource = collectionProtocol
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.register(HWGiftBagCenterCell.self, forCellWithReuseIdentifier: "HWGiftBagCenterCell")
        view.addSubview(collectionView)
        collectionView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        collectionView.ly_emptyView.contentViewOffset = -40
    }
    
    private func initFrame() -> Void {
        searchBgView.snp.makeConstraints { make in
            make.left.equalTo(18*widthScale)
            make.right.equalTo(-18*widthScale)
            make.top.equalTo(navigationView.snp.bottom).offset(9*widthScale)
            make.height.equalTo(34*widthScale)
        }
        
        searchLogo.snp.makeConstraints { make in
            make.left.equalTo(10*widthScale)
            make.width.height.equalTo(14*widthScale)
            make.centerY.equalToSuperview()
        }
        
        searchField.snp.makeConstraints { make in
            make.left.equalTo(searchLogo.snp.right).offset(4*widthScale)
            make.centerY.equalToSuperview()
            make.height.equalTo(18*widthScale)
            make.right.equalTo(-18*widthScale)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(searchBgView.snp.bottom)
        }
        
    }
}

extension HWGiftBagCenterController {
    func loadData() -> Void {
        self.collectionView.mj_footer?.endRefreshing()
        httpManager.getGiftBagCenterList(type: "0", keyword: keyword) { models in
            self.modelArr = models
            self.collectionProtocol.models = models
            self.collectionView.reloadData()
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.isHidden = false
        } failure: { errorString in
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            self.view.showHUD(title: errorString)
        }

    }
    
    func addRefresh() -> () {
        
        collectionView.mj_header = MJRefreshNormalHeader()
        collectionView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        collectionView.mj_footer = MJRefreshBackNormalFooter()
        collectionView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        collectionView.mj_footer?.isHidden = true
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.collectionView.mj_footer?.endRefreshing()
        httpManager.getGiftBagCenterListFooter(type: "0", keyword: keyword) { models in
            self.collectionView.mj_footer?.endRefreshing()
            if models.count > 0 {
                for mod in models {
                    self.modelArr.append(mod)
                }
            }
            self.collectionProtocol.models = self.modelArr
            self.collectionView.reloadData()
        } failure: { error in
            self.collectionView.mj_footer?.endRefreshing()
        }
    }
}

extension HWGiftBagCenterController:UITextFieldDelegate {
    @objc func searchTextFieldChange(_ textField:UITextField) ->Void {
        if textField.text?.count == 0 {
            keyword = ""
            loadData()
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        textField.endEditing(true)
        keyword = textField.text ?? ""
        loadData()
        return true
    }
}

extension HWGiftBagCenterController {
    func addAction() -> Void {
        collectionProtocol.clickItem = {
            mod in
            self.loadGiftBagDetail(mod)
            
        }
    }
    
    func loadGiftBagDetail(_ mod:HWGiftBagCenterModel) -> Void {
        self.view.showHUD(title: "请稍候")
        self.httpManager.getGiftBagCenterDetail(gid: mod.gid) { model in
            self.hideHUD()
            
            self.alert.model = model
            if self.alert.isShow {
                
            } else {
                self.alert.show()
            }
            
            self.alert.receiveButtonClick = {
                id in
                self.httpManager.getGiftBagReceive(id: id) { success in
                    self.loadGiftBagDetail(mod)
                } failure: { errorString in
                    self.view.showHUD(title: errorString)
                }

            }
            
            self.alert.copyButtonClick = {
                code in
                let pasteBoard =  UIPasteboard.general
                pasteBoard.string = code
                self.alert.showHUD(title: "礼包码已复制")
            }
            
        } failure: { errorString in
            self.hideHUD()
        }
    }
}
